<script setup>
import { getProductThroughputRate } from '@/api/visual/productionBoard'
import { fontSize } from '@/utils/globalMethod.js'

const key = ref(1)
const optionData = ref([])
const xAxisData = ref([])
const props = defineProps({
  // 将变量名改为props（复数形式）
  activeLineID: {
    type: String,
    default: ''
  },
  active: {
    type: String,
    default: ''
  }
})

const option = computed(() => ({
  title: {
    text: '产品直通率',
    textStyle: {
      color: '#fff',
      fontSize: fontSize(0.16)
    }
  },
  xAxis: {
    type: 'category',
    data: xAxisData.value,
    axisLabel: {
      color: '#ccc1c1'
    }
  },
  yAxis: {
    type: 'value',
    splitLine: {
      lineStyle: {
        color: '#2b2c33'
      }
    },
    axisLabel: {
      color: '#ccc1c1'
    }
  },
  legend: {
    right: '0',
    textStyle: {
      color: '#ccc1c1'
    }
  },
  grid: {
    bottom: '15%',
    top: '20%',
    left: '15%'
  },
  series: optionData.value
}))
const getLast7Days = () => {
  const days = []
  const today = new Date()

  for (let i = 6; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(today.getDate() - i)

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    days.push(`${year}${month}${day}`)
  }
  return days
}
const aggregateData = data => {
  const aggregated = {}
  data.forEach(item => {
    const { BillDate, Quantity, GoodQty } = item
    const dateKey = BillDate

    if (!aggregated[dateKey]) {
      aggregated[dateKey] = {
        BillDate,
        Quantity: 0,
        GoodQty: 0
      }
    }

    aggregated[dateKey].Quantity += Quantity
    aggregated[dateKey].GoodQty += GoodQty
  })

  // 将对象转换为数组
  return Object.values(aggregated)
}
const loadData = async () => {
  let { data } = await getProductThroughputRate({ LineName: props.activeLineID, OrderID: props.active })
  data = aggregateData(data)
  xAxisData.value = getLast7Days()
  const matchedData = xAxisData.value.map(date => {
    // 将横坐标轴的日期转换为数字类型，以便与后端数据匹配
    const dateNum = parseInt(date)
    // 查找匹配的后端数据
    const matchedItem = data.find(item => item.BillDate === dateNum)
    if (matchedItem) {
      return {
        date,
        Quantity: matchedItem.Quantity,
        GoodQty: matchedItem.GoodQty
      }
    } else {
      return {
        date,
        Quantity: 0,
        GoodQty: 0
      }
    }
  })

  optionData.value = {
    data: [
      matchedData[0].Quantity === 0
        ? 0
        : ((Number(matchedData[0].GoodQty) / Number(matchedData[0].Quantity)) * 100).toFixed(2),
      matchedData[1].Quantity === 0
        ? 0
        : ((Number(matchedData[1].GoodQty) / Number(matchedData[1].Quantity)) * 100).toFixed(2),
      matchedData[2].Quantity === 0
        ? 0
        : ((Number(matchedData[2].GoodQty) / Number(matchedData[2].Quantity)) * 100).toFixed(2),
      matchedData[3].Quantity === 0
        ? 0
        : ((Number(matchedData[3].GoodQty) / Number(matchedData[3].Quantity)) * 100).toFixed(2),
      matchedData[4].Quantity === 0
        ? 0
        : ((Number(matchedData[4].GoodQty) / Number(matchedData[4].Quantity)) * 100).toFixed(2),
      matchedData[5].Quantity === 0
        ? 0
        : ((Number(matchedData[5].GoodQty) / Number(matchedData[5].Quantity)) * 100).toFixed(2),
      matchedData[6].Quantity === 0
        ? 0
        : ((Number(matchedData[6].GoodQty) / Number(matchedData[6].Quantity)) * 100).toFixed(2)
    ],
    stack: 'a',
    type: 'line',
    smooth: true,
    label: {
      show: true,
      position: 'top',
      color: '#fff',
      textStyle: {
        fontSize: fontSize(0.12)
      }
    }
  }
}
const keyResize = () => {
  nextTick(() => {
    setTimeout(() => {
      key.value++
    }, 100)
  })
}
watch(
  () => [props.activeLineID, props.active], // 使用正确的变量名props
  async (newValues, oldValues) => {
    if (newValues !== oldValues || newValues !== oldValues) {
      await loadData()
    }
  },
  { immediate: true }
)
onMounted(loadData)

onMounted(() => {
  window.addEventListener('resize', keyResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', keyResize)
})
</script>

<template>
  <div class="ps_w_h_100">
    <dv-border-box13 class="ps_pd10" :key="key">
      <ps-chart2 :option="option"></ps-chart2>
    </dv-border-box13>
  </div>
</template>

<style scoped lang="scss"></style>
